/**
 * Created by Xiaoming on 2017/8/30.
 */
angular.module('service.wxauth', [
        "ngResource"
    ])
    .service('WxAuthService', WxAuthService);
WxAuthService.$inject = ['$resource','$cookies'];
function WxAuthService($resource,$cookies) {
    var wxOpenid;
    var wxAuth;
    //获取微信支付OpenID
    this.getOpenid = function () {
        if (!wxOpenid) {
            var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            var authcode = "xxxxxxxxxxxxxxxxxx";
            if (r) {
                authcode = unescape(r[2]);
                var openid_res;
                //if(){
                //
                //}
                if($cookies.get("appid")){
                    $cookies.get("appid");
                    mall_userauth.wxmp_appid = $cookies.get("appid");
                }
                if (mall_userauth.component_appid) {
                    openid_res = $resource(mall_userauth.memopen_url + "jsapi/webauth").save({
                        component_appid: mall_userauth.component_appid,
                        mer_id: mall_userauth.wxmp_appid,
                        code: authcode
                    });
                } else {
                    openid_res = $resource(mall_userauth.userauth_url + "wxauth/openid").get({
                        appid: mall_userauth.wxmp_appid,
                        code: authcode
                    });
                }
                openid_res.$promise.then(function (data) {
                    if (data.openid) {
                        wxOpenid = data.openid;
                        $cookies.put("openid",wxOpenid);
                    } else {
                        console.log("can't get openid by code=" + authcode);
                    }
                }, function (error) {
                    console.log("code is invalid");
                });
                return openid_res;
            } else {
                return wxOpenid;
            }
        } else {
            return wxOpenid;
        }
    };

    //获取微信用户信息
    this.getUserinfo = function () {
        var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        var authcode = "xxxxxxxxxxxxxxxxxx";
        if (r) {
            authcode = unescape(r[2]);
            var userinfo_res;
            if($cookies.get("appid")){
                $cookies.get("appid");
                mall_userauth.wxmp_appid = $cookies.get("appid");
            }
            if (mall_userauth.component_appid) {
                userinfo_res = $resource(mall_userauth.memopen_url + tempwxuserinfo).save({
                    component_appid: mall_userauth.component_appid,
                    mer_id: mall_userauth.wxmp_appid,
                    code: authcode
                });
            } else {
                userinfo_res = $resource(mall_userauth.userauth_url + "wxauth/userinfo").get({
                    appid: mall_userauth.wxmp_appid,
                    code: authcode
                });
            }
            userinfo_res.$promise.then(function (data) {
                $cookies.put("openid",data.openid);
                wxAuth = data;
                wxAuth.newuser = true;
            }, function (error) {
                console.log("code is invalid");
            });
            return userinfo_res;
        } else {
            return "code is invalid";
        }
    };

    // 尝试微信登录
    this.wxTryLogin = function(login_func, success_cbfunc, error_cbfunc) {
        var self = this;
        // try login with openid
        var openid = self.getOpenid();
        if (typeof (openid) == "object") {
            openid.$promise.then(function (data) {
                login_func(data.openid,function (userinfo) {
                    success_cbfunc(userinfo);
                }, function (error) {
                    if (typeof (error_cbfunc) == "function") {
                        error_cbfunc(error, data.openid);
                    }
                });
            }, function (error) {
                alert(JSON.stringify(error));
            });
        } else if (openid) {
            login_func(openid,function (userinfo) {
                success_cbfunc(userinfo);
            }, function (error) {
                if (typeof (error_cbfunc) == "function") {
                    error_cbfunc(error, openid);
                }
            });
        } else {
            //alert("wxTryLogin() openid is empty");
        }
    };

    // 尝试微信登录或跳转注册
    this.wxTryLoginOrRegist = function(redirect_uri, login_func, success_cbfunc, error_cbfunc) {
        var self = this;
        var openid = self.getOpenid();
        if (typeof (openid) == "object") {
            openid.$promise.then(function (data) {
                login_func(data.openid,function (userinfo) {
                    success_cbfunc(userinfo);
                }, function (error) {
                    if (typeof (error_cbfunc) == "function") {
                        error_cbfunc(error, data.openid);
                    }
                    self.wxAuthJump(redirect_uri);
                });
            }, function (error) {
                self.wxAuthJump(redirect_uri);
            });
        } else if (openid) {
            login_func(openid,function (userinfo) {
                success_cbfunc(userinfo);
            }, function (error) {
                if (typeof (error_cbfunc) == "function") {
                    error_cbfunc(error, openid);
                }
                self.wxAuthJump(redirect_uri);
            });
        } else {
            self.wxAuthJump(redirect_uri);
        }
    };

    // 跳转微信授权以获取用户openid
    this.wxOpenidJump = function (redirect_uri) {
        var authorize_url = "";
        if($cookies.get("appid")){
            $cookies.get("appid");
            mall_userauth.wxmp_appid = $cookies.get("appid");
        }
        var appid = mall_userauth.wxmp_appid;
        if (mall_userauth.component_appid) {
            var newuri = redirect_uri;
            //alert(newuri);
            authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(newuri) + "&response_type=code&scope=snsapi_base&state=2015&component_appid="+mall_userauth.component_appid+"#wechat_redirect";
        } else {
            authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(redirect_uri) + "&response_type=code&scope=snsapi_base&state=2015#wechat_redirect";
        }
        //
        window.location.href = authorize_url;
    };

    // 跳转微信授权以获取用户信息
    this.wxAuthJump = function (redirect_uri) {
        var authorize_url = "";
        if($cookies.get("appid")){
            $cookies.get("appid");
            mall_userauth.wxmp_appid = $cookies.get("appid");
        }
        var appid = mall_userauth.wxmp_appid;
        if (mall_userauth.component_appid) {
            var newuri = redirect_uri;
            //alert(newuri);
            authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(newuri) + "&response_type=code&scope=snsapi_userinfo&state=1314&component_appid="+mall_userauth.component_appid+"#wechat_redirect";
        } else {
            authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(redirect_uri) + "&response_type=code&scope=snsapi_userinfo&state=1314#wechat_redirect";
        }
        //
        window.location.href = authorize_url;
    };
}